import dayjs from "dayjs";
importClass('android.view.WindowManager');
importClass("android.view.Gravity");
importClass("android.graphics.PixelFormat");
declare const WindowManager: any;
import { getLiveRoomInfo } from "./v3/getLiveRoomInfo";
import { getRedPacketInfo } from "./v3/getRedPacketInfo";
import { getSafeClip } from "./v3/getSafeClip";
import { clearDialog } from "./v3/clearDialog";
import { FloatyWindow } from "floaty";
import { View } from "ui";
import { Thread } from "threads";

auto.waitFor();
const config = storages.create(`com.sker.auto`)
const emitter = events.emitter()
let sleepTime: number = 0;
let packagename: string = `com.smile.gifmaker`;
let total: number = 0;
let success: number = 0;
let fail: number = 0;
let isDev: boolean = false;
let allThreads: Thread[] = [];
let window: FloatyWindow & {
    [prop: string]: View;
};
const interval = setInterval(() => { }, 1000 * 30)

events.on('exit', () => {
    if (allThreads && allThreads.length > 0) {
        allThreads.map(thread => {
            if (thread.isAlive()) {
                thread.interrupt()
            }
        })
    }
    if (interval) clearInterval(interval)
    safeRun(() => emitter.removeAllListeners())
    safeRun(() => window && window.exitOnClose())
    safeRun(() => config.remove('MINE_TASK'))
})
config.remove('MINE_TASK')

render()
runThread();
function runThread() {
    const thread = threads.start(() => {
        if (getCurrentPackage() !== packagename) {
            openKsLive()
            const yunxu = selector().textContains(`允许`).visibleToUser(true).findOne(1000 * 5)
            yunxu && clickButton(yunxu)
        }
        toHome();
        // 去直播间
        clickButton(selector().textMatches(/首页/).visibleToUser(true).findOne(1000 * 10))
        clearDialog();
        sleep(3000)
        selectButton(selector().descMatches(/直播|小说|热门|放映厅|探索|生活/).visibleToUser(true).findOne(1000 * 3))
        clearDialog();
        sleep(3000)
        selectButton(selector().textMatches(/直播/).visibleToUser(true).findOne(1000 * 3))
        clearDialog();
        sleep(3000)
        selectButton(selector().textMatches(/直播中|游戏直播|直播卖货/).visibleToUser(true).findOne(1000 * 3))
        clearDialog();
        selectButton(selector().textMatches(/直播中|游戏直播|直播卖货/).visibleToUser(true).findOne(1000 * 3))
        clearDialog();
        while (true) {
            if (isSleep()) {
                while (getCurrentPackage() === packagename) {
                    back();
                    sleep(3000)
                    clearDialog();
                    if (selector().descMatches(/首页|精选|消息|我/).findOne(1000 * 10)) {
                        home();
                    }
                }
            }
            while (isSleep()) {
                sleepTime += 1;
                updateFloat({ toast: `夜间休息${formatMinute(sleepTime)}`, tip: ``, currentTask: `夜间休息`, currentResult: formatMinute(sleepTime) })
                sleep(1000)
            }
            run();
        }
    })
    allThreads.push(thread)
}

function run() {
    try {
        total += 1;
        updateFloat({ total: `${total}`, currentTask: `抓包`, toast: `正在进行抓包...`, currentResult: `第${total}个` })
        clearDialog();
        const liveRoomInfo = getLiveRoomInfo()
        if (liveRoomInfo) {
            safeRun(() => liveRoomInfo?.open())
            sleep(3000)
            // 有红包
            const redPacketInfo = getRedPacketInfo()
            sleep(1000)
            safeRun(() => redPacketInfo?.close())
            let maxCount: number = 0;
            const redPackets = redPacketInfo.redPackets?.filter(red => {
                if (red.count > maxCount) {
                    maxCount = red.count;
                }
                if (red.type === '口令') {
                    return true;
                }
                if (red.type === '快币') {
                    return true;
                }
                if (red.type === '穿云箭') {
                    return true;
                }
                if (red.type === '粉丝') {
                    return true;
                }
                if (red.type === '分享') {
                    return true;
                }
                return false;
            });
            if (redPackets && redPackets.length > 0) {
                if (!clickButton(selector().idContains('live_bottom_bar_single_icon_container').visibleToUser(true).findOne(10 * 1000))) {
                    return;
                }
                sleep(2000)
                if (!clickButton(selector().textContains('分享').visibleToUser(true).findOne(10 * 1000))) {
                    return;
                }
                sleep(2000)
                if (!clickButton(selector().textContains('复制链接').visibleToUser(true).findOne(10 * 1000))) {
                    return;
                }
                sleep(1000)
                const link = getSafeClip()
                clearDialog();
                const res = link.match(/(http.*?) (.*?)的直播/)
                if (res && res.length > 0) {
                    const link = res[1]
                    const name = res[2]
                    const { openTime, heartCount, online, category, redPacketCount } = liveRoomInfo;
                    const data = {
                        openTime,
                        heartCount,
                        online,
                        category,
                        redPacketCount,
                        redPackets,
                        link,
                        name,
                        maxCount,
                        uuid: config.get('DEVICE_UUID')
                    }
                    success += 1;
                    updateFloat({ success: `${success}` })
                    httpPost('addRedPkg', data)
                    return;
                }
                return;
            }
        }
    } catch (e) {
        fail += 1;
        updateFloat({ fail: `${success}`, tip: `${dayjs().format('HH:mm:ss')} ${e.message} ${e.stack}` })
        clearDialog();
    } finally {
        clearDialog();
        sleep(1000)
        const scrollableNode = selector().scrollable().findOne()
        if (scrollableNode) {
            // 导入AutoJS依赖
            const height = device.height;
            const width = device.width;
            // 模拟上划操作
            swipe(width / 2, height * 4 / 5, width / 2, height / 10, 300);
        }
    }
}

function safeRun(fn: Function) {
    try {
        fn()
        return true;
    } catch (e) {
        return false;
    }
}

function clickButton(btn: UiObject) {
    if (!btn) return false;
    if (btn.clickable()) {
        return btn?.click()
    } else {
        const bounds = btn.bounds();
        click(bounds.centerX(), bounds.centerY());
        return true;
    }
}


function selectButton(btn: UiObject) {
    if (!btn) return false;
    if (btn.selected()) {
        return true;
    } else {
        return clickButton(btn)
    }
}

function formatNumber(val: number) {
    if (val < 10) return `0${val}`
    return `${val}`
}
function formatMinute(value: number) {
    if (value <= 0) return `00:00`
    value = parseInt(`${value}`)
    const minute = Math.floor(value / 60)
    const second = value % 60;
    return `${formatNumber(minute)}:${formatNumber(second)}`
}
function isSleep() {
    if (isDev) return false;
    const now = dayjs()
    const hour = now.get('hour')
    if (hour >= 23) {
        // 休息
        return true;
    }
    if (hour < 8) {
        // 休息
        return true;
    }
    return false;
}
function getCurrentPackage() {
    return selector().visibleToUser(true).findOne()?.packageName()
}
function httpPost(path: string, body: object) {
    const host = `60.204.248.43`
    const port = 3102
    let url: string = path;
    if (!url.startsWith(`http`)) {
        url = `http://${host}:${port}/autojs/core/autox/${path}`
    }
    const res = http.post(url, body, {
        timeout: 5 * 1000,
        contentType: 'application/json'
    })
    if (res.statusCode !== 200) {
        throw new Error(`请求失败`);
    }
    if (res.headers["Content-Type"].includes('text/html')) {
        throw new Error(`请求失败ContentType类型有误`);
    }
    const resData: any = res.body.json();
    const { success, message, data } = resData;
    if (success) {
        return data;
    } else {
        throw new Error(message)
    }
}

function render(): void {
    if (!floaty.checkPermission()) {
        floaty.requestPermission();
    }
    floaty.closeAll()
    window = floaty.window(`<frame id="main" w="*" h="*" bg="#000000" alpha="0">
    <vertical w="*" h="*">
        <horizontal padding="0 0 0 0">
            <text w="*" padding="15 5 15 5" bg="#130B2E" h="auto" id="toast" textSize="16" gravity="center" text="" textColor="#D12E2E"/>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <text w="auto" textSize="12" gravity="left" text="当前任务：" textColor="#E2E1CF"/>
            <text w="*" id="currentTask" textSize="14" gravity="left" text="-" textColor="#f29a8c"/>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <text w="auto" textSize="12" gravity="left" text="执行结果：" textColor="#F2F2F2"/>
            <text w="*" id="currentResult" textSize="14" gravity="left" text="-" textColor="#f29a8c"/>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="成功：" textColor="#F2F2F2"/>
                <text w="*" id="success" textSize="14" gravity="left" text="-" textColor="#f29a8c"/>
            </horizontal>
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="失败：" textColor="#F2F2F2"/>
                <text w="*" id="fail" textSize="14" gravity="left" text="-" textColor="#f29a8c"/>
            </horizontal>
            <horizontal layout_weight="1">
                <text w="auto" textSize="12" gravity="left" text="总数：" textColor="#F2F2F2"/>
                <text w="*" id="total" textSize="14" gravity="left" text="-" textColor="#f29a8c"/>
            </horizontal>
        </horizontal>
        <horizontal padding="15 5 15 5">
            <text w="*" id="tip" textSize="12" gravity="center" text="-" textColor="#f29a8c"/>
        </horizontal>
    </vertical>
</frame>`)
    const uitask = threads.start(() => {
        ui.run(() => {
            const parentParent = window.main.parent.parent.parent;
            let params = parentParent.layoutParams || {};
            if (params.flags == 16777736) {
                log("当前可以触摸, 修改为不可触摸");
                params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            } else if (params.flags == 16777752) {
                log("当前不可以触摸, 修改为可触摸");
                params.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
            }
            const windowManager = context.getSystemService(context.WINDOW_SERVICE);
            windowManager.updateViewLayout(parentParent, params);
            const w = window;
            let wh = w.getHeight();
            let dw = device.width;
            let dh = device.height;
            w.setSize(dw + 100, wh);
            w.main.attr('alpha', .9)
            // 悬浮窗置于底部中央
            let y = dh - wh;
            w.setPosition(0, y);
        })
    })
    uitask.waitFor()
    uitask.join()
    uitask.interrupt()
    const updateUi = (state: any) => {
        ui.run(() => {
            Object.keys(state).map(key => {
                const val = state[key]
                window.findView(key)?.setText(`${val}`)
            })
        })
    }
    emitter.on('UPDATE_FLOAT_WINDOW_STATE_CHANGE', (val: any) => {
        const storage: any = config.get(`MINE_TASK`, {});
        const state = {
            currentTask: '抓包',
            ...storage,
            ...val,
        };
        config.put(`MINE_TASK`, state)
        updateUi(state)
    });
}

function updateFloat(data: { currentTask?: string, currentResult?: string, tip?: string, toast?: string, success?: string, fail?: string, total?: string }) {
    emitter.emit('UPDATE_FLOAT_WINDOW_STATE_CHANGE', data)
}

function openKsLive(signal: boolean = true) {
    // let flag: any = signal ? Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK : Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
    // const uri = `kwai://liveaggregatesquare`
    // const intent = app.intent({
    //     action: "android.intent.action.VIEW",
    //     data: uri,
    //     flags: flag
    // });
    // context.startActivity(intent);
    app.launchPackage(packagename);
    sleep(1000 * 8);
    clearDialog();

}

function toHome() {
    while (getCurrentPackage() === packagename) {
        back();
        sleep(3000)
        clearDialog();
        if (selector().descMatches(/首页|精选|消息|我/).findOne(1000 * 10)) {
            break;
        }
    }
}